package org.vectrics.recruiter.struts.tag;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ecs.html.A;
import org.apache.ecs.html.TextArea;
import org.apache.log4j.Logger;
import org.vectrics.DataException;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.common.view.SimpleForm;
import org.vectrics.location.Address;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.struts.SaveTextResumeAction;
import org.vectrics.recruiter.user.RecruitUserProfile;
import org.vectrics.recruiter.user.UserEmployment;
import org.vectrics.skill.Skill;
import org.vectrics.skill.SkillRating;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.ContactInfo;
import org.vectrics.user.Person;

public class UserResumeTag extends VectricsTagSupport {
	public static final long serialVersionUID = 64363777345542L;
	
    private transient static Logger log = Logger.getLogger(UserResumeTag.class);
    private RecruitUserProfile userProfile = null;
    private SimpleDateFormat jobDateFormat = new SimpleDateFormat("MM-yyyy");
    private static int SECTION_WIDTH = 400;
    private String contextRoot = null;
    
	public String getContextRoot() {
		return(contextRoot);
	}    

	public String makeStartTag() {
    	
        log.debug("doRender() called");
		ServletRequest servletRequest = super.pageContext.getRequest();
		HttpSession session = super.pageContext.getSession();
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        contextRoot = request.getContextPath();
		Person user = null;
		try {
			user = this.getAuthPerson();
		}
		catch (Exception ex) {
			log.error("Exception finding auth user", ex);
			throw new SystemException("Exception finding auth user", ex);
		}
        Table mainTable = new Table();
        Row mainRow = mainTable.addRow();
        Cell mainCell = mainRow.addCell();
        
        Table table = new Table();
        table.setWidth(400);
        
        Row row = table.addRow();
        Cell cell = row.addCell();
        cell.addElement(TextHelper.getFont("stdFont", "<b>User Name</b>"));
        cell = row.addCell();
        cell.addElement(TextHelper.getFont("stdFont", user.getUser().getUserName()));
        
        row = table.addRow();
        cell = row.addCell();
        cell.setWidth(150);
        mainCell.addElement(TextHelper.getFont("stdFont", "<b>Full Name</b>"));
        cell = row.addCell();
        cell.addElement(TextHelper.getFont("stdFont", user.getFirstName() + " "
                + user.getLastName()));

        mainCell.addElement("<br><br>"); 

        makeTextResumeForm(request, mainCell, user);
        
        BorderTable contactTable = new BorderTable();
        contactTable.setWidth(SECTION_WIDTH);
        Row contactRow = contactTable.addRow();
        Cell contactCell = contactRow.addCell();
        contactCell.setClass("xltGray");
        contactCell.addElement(TextHelper.getFont("stdFont", "<b>Contact Information</b>"));
        contactRow = contactTable.addRow();
        contactCell = contactRow.addCell();
        mainCell.addElement(contactTable);
        contactCell.addElement(getContactTable(request, user.getContactInfo()));

        mainCell.addElement("<br><br>"); 
        makeSkillSummary(request, mainCell);
        
        mainCell.addElement("<br><br>"); 
        try {
        	makeEmploymentCell(mainCell, user);
        }
        catch (DataException de) {
        	log.error("DataException displaying employments", de);
        }
        
		return(mainTable.toString());
        
    }
    
    
    protected void makeTextResumeForm(HttpServletRequest request, Cell mainCell, Person person) {
		Properties props = new Properties();
		Properties invalidProps = new Properties();
        SimpleForm form = new SimpleForm(props, invalidProps);

        form.setMethod("GET");
        String resumeText = userProfile.getRecruitUserComponent().getResume().getTextResume();
        
        mainCell.addElement(form.toString());
        form.setAction("/" + request.getContextPath() +  "/profile/user/resume");
        form.addHidden(SaveTextResumeAction.USER_NAME_PARAM, userProfile.getUserName());

        TextArea descEntry = new TextArea();
        descEntry.setRows(40);
        descEntry.setCols(80);
        descEntry.setStyle("font-family:verdana,arial,sans serif;font-size:" +
        		"10px");
        descEntry.addElement(resumeText);
        
        form.addTextAreaRow("Description", 
        		SaveTextResumeAction.RESUME_TEXT_PARAM, 
        		descEntry, false);
        		
        form.addSubmitButton("Submit", null);
    }

    
    protected Table getContactTable(HttpServletRequest request, ContactInfo contactInfo) {
        log.debug("getContactTable() - building a table containing contact info");
        Table table = new Table();
        makeFieldRow(table, "E-Mail", contactInfo.getEmail());
        makeFieldRow(table, "E-Mail 2", contactInfo.getEmail2());
		if (contactInfo.getHomePhone() != null)
			makeFieldRow(table, "Home Phone", contactInfo.getHomePhone().getFormattedNumber());
		if (contactInfo.getWorkPhone() != null)
			makeFieldRow(table, "Work Phone", contactInfo.getWorkPhone().getFormattedNumber());
       return(table);
    }
    
    
    private Row makeFieldRow(Table table, String caption, String value) {
        log.debug("makeFieldRow() - creating display field in row of html table");
        if ((value == null) || (value.trim().equals(""))) {
            value = "<i>Not Given</i>";
        }
        Row row = table.addRow();
        Cell cell = row.addCell();
        cell.setVAlign("top");
        cell.addElement(TextHelper.getFont("stdFont", "<b>" + caption + "</b>"));
        cell = row.addCell();
        cell.addElement("&nbsp;");
        cell = row.addCell();
        cell.addElement(TextHelper.getFont("stdFont", value));
        return(row);
    }
    
    
   private String getAddressHtml(Address address) {
       log.debug("getAddressHtml() called");
       String str = "<i>No Address Entered</i>";
       if (address != null) {
           if ((address.getAddress1() != null) && (address.getAddress1().length() > 0))
               str = TextHelper.escapeHtml(address.getAddress1()) + "<br>";
           if ((address.getAddress2() != null) && (address.getAddress2().length() > 0))
               str += TextHelper.escapeHtml(address.getAddress2()) + "<br>";
           if ((address.getCity() != null) && (address.getCity().length() > 0))
               str += TextHelper.escapeHtml(address.getCity()) + ", ";
           if ((address.getState() != null) && (address.getState().length() > 0))
               str += TextHelper.escapeHtml(address.getState()) + ", ";
           if ((address.getPostalCode() != null) && (address.getPostalCode().length() > 0))
               str += TextHelper.escapeHtml(address.getState()) + "&nbsp;&nbsp;";
           if (str.length() > 0) {
               str += "<br>";
           }
           if ((address.getCountryCode() != null) && (address.getCountryCode().length() > 0))
               str += TextHelper.escapeHtml(address.getCountryCode()) + "&nbsp;&nbsp;";

           if (str.length() <= 0) {
               str = "<i>No Address Entered</i>";
           }
       }
       return(str);
   }

   
   protected void makeSkillSummary(ServletRequest request, Cell mainCell) {
        log.debug("makeSkillSummary() called");
        
        Table skillTable = new BorderTable();
        skillTable.setWidth(SECTION_WIDTH);
        Row contactRow = skillTable.addRow();
        Cell contactCell = contactRow.addCell();
        contactCell.setClass("xltGray");
        contactCell.addElement(TextHelper.getFont("stdFont", "<b>Skills Assessment</b>"));
        
        contactRow = skillTable.addRow();
        contactCell = contactRow.addCell();
        mainCell.addElement(skillTable);
        
        int numSkills = 0;
        try {
            numSkills = userProfile.getUserSkillSet().size();
        }
        catch (Exception ex) {
            log.error("doRender() - exception retrieving user skill set.", ex);
        }
        
        if (numSkills > 0) {
            contactCell.addElement(TextHelper.getFont("stdFont", numSkills 
                    + " skills entered.<br><br>"));
            try {
                // Display user's skills
                BorderTable skillsTable = new BorderTable();
                contactCell.addElement(skillsTable);
                skillsTable.setWidth("95%");
                Iterator iter = userProfile.getUserSkillSet().iterator();
                while (iter.hasNext()) {
                    Row skillRow = skillsTable.addRow();
                    Cell cell_1 = skillRow.addCell();
                    cell_1.setWidth("50%");
                    Cell cell_2 = skillRow.addCell();
                    cell_2.setWidth("50%");
                    SkillRating userSkill = (SkillRating)iter.next();
                    makeSkillCell(userSkill, cell_1);
                    if (iter.hasNext()) {
                        userSkill = (SkillRating)iter.next();
                        makeSkillCell(userSkill, cell_2);
                    }
                }
            }
            catch (java.lang.Exception ex) {
                log.error("Error occurred displaying user skill summary.", ex);
                contactCell.addElement(TextHelper.getFont("errorFont", "Error occurred displaying user skill summary."));
            }
        }
        else {
            contactCell.addElement(TextHelper.getFont("stdFont", "No skills have been entered.<br><br>"));
        }
        contactCell.addElement("<br>");
        
        A link = new A();
        link.setHref("/hrs-public/profile/skills/show.do");
        link.setClass("subLink");
        link.addElement("View Skill Tree");
        contactCell.addElement(link);

        contactCell.addElement("&nbsp;");

        link = new A();
        link.setHref("/hrs-public/profile/skills/edit.do");
        link.setClass("subLink");
        link.addElement("Change Skills");
        contactCell.addElement(link);
    }
    
    protected void makeSkillCell(SkillRating rating, Cell cell) {
        log.debug("makeSkillCell() called");
        Skill skill = rating.getSkill();
        cell.addElement(TextHelper.getFont("subFont", skill.getDescription()));
    }

	
    protected void makeEmploymentCell(Cell mainCell, Person user) {
        log.debug("makeEmploymentCell() - called");
        Collection employmentList = RecruitServiceLocator.getRecruitUserService().getEmployments(user);
        Iterator iter = employmentList.iterator();
        BorderTable empTable = new BorderTable();
        empTable.setWidth(SECTION_WIDTH);
        Row hdrRow = empTable.addRow();
        Cell hdrCell = hdrRow.addCell();
        hdrCell.setClass("xltGray");
        hdrCell.addElement(TextHelper.getFont("stdFont", "<b>Employment History</b>"));
        mainCell.addElement(empTable);

        Row row = empTable.addRow();
        Cell contentCell = row.addCell();
        contentCell.addElement("<br>");
        
        if (iter.hasNext()) {
            
            Table innerTable = new Table();
            row = innerTable.addRow();
            Cell cell = row.addCell();
            cell.addElement(TextHelper.getFont("subFont", "<b>Title</b>"));
            cell = row.addCell();
            cell.addElement(TextHelper.getFont("subFont", "<b>Title</b>"));
            while (iter.hasNext()) {
                UserEmployment emp = (UserEmployment)iter.next();
                log.debug("makeEmploymentCell() - displaying an employment entry");
                row = innerTable.addRow();
                cell.addElement(TextHelper.getFont("subFont", emp.getTitle()));
                cell = row.addCell();
                cell.addElement(TextHelper.getFont("subFont", emp.getCompanyName()));
                
                String startDateStr = "?";
                String endDateStr = "Present";
                if (emp.getStartDate() != null) {
                    startDateStr = jobDateFormat.format(emp.getStartDate());
                }
                if (emp.getEndDate() != null) {
                    endDateStr = jobDateFormat.format(emp.getEndDate());
                }
                
                cell = row.addCell();
                cell.addElement(TextHelper.getFont("subFont", startDateStr));
                cell = row.addCell();
                cell.addElement(TextHelper.getFont("subFont", endDateStr));
            }
        }
        else {
            log.debug("makeEmploymentCell() - no employment entries found for user: " 
                    + user.getUser().getUserName());
            contentCell.addElement(TextHelper.getFont("subFont", "<br><i>You have not entered your employment history.</i>"));
        }
        contentCell.addElement("<br><br>");

        A link = new A();
        link.setHref(getContextRoot() + "/profile/employment/edit.do");
        link.setClass("subLink");
        link.addElement("Add Employment Entry");
        contentCell.addElement(link);
        
    }
    
}